package com.niit.chat.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@Component
public class QiniuUtil {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.domain}")
    private String domain;

    public String uploadFile(InputStream inputStream, String fileName) throws Exception {
        try {
            Configuration cfg = new Configuration();
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            // 生成唯一文件名，使用原始文件名
            String key = UUID.randomUUID().toString() + "_" + fileName;

            Response response = uploadManager.put(inputStream, key, upToken, null, null);
            if (response.isOK()) {
                // 拼接外链，让URL构造函数处理编码
                return new URL(new URL(domain), key).toString();
            } else {
                return response.error;
            }
        } catch (QiniuException ex) {
            Response r = ex.response;
            throw new QiniuException(r);
        }
    }
}